from pynput import keyboard
from threading import Thread

class KeyboardCatch:
    def __init__(self):
        self.key_states = {
            "w": False, "a": False, 
            "s": False, "d": False, 
            "q": False, "e": False, 
            "r": False, "f": False,
            "x": False, "c": False, "esc": False
        }
    # 启动键盘监听
    def run_keyboard_listener(self):
        # 启动捕获按键的线程
        self.key_thread = Thread(target=self.__capture_keys, daemon=True)
        self.key_thread.start()
    # 键盘监听函数
    def __on_press(self, key):
        try:
            if key.char in self.key_states:
                self.key_states[key.char] = True
        except AttributeError:
            pass
        if key == keyboard.Key.esc:
            self.key_states['esc'] = True
    def __on_release(self, key):
        try:
            if key.char in self.key_states:
                self.key_states[key.char] = False
        except AttributeError:
            pass
        if key == keyboard.Key.esc:
            self.key_states['esc'] = False
    # 捕获按键的线程函数
    def __capture_keys(self):
        with keyboard.Listener(on_press=self.__on_press, on_release=self.__on_release) as listener:
            listener.join()
    def show_key_states(self):
        print(self.key_states)
    def get_key_states(self):
        return self.key_states
        
if __name__ == "__main__":
    keyboard_catch = KeyboardCatch()
    keyboard_catch.run_keyboard_listener()
    while True:
        keyboard_catch.show_key_states()